import { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { formatFileSize, isSupportedFileType } from "@/lib/utils";
import { SUPPORTED_FILE_TYPES, MAX_FILE_SIZE } from "@/lib/constants";

interface FileUploadProps {
  onUpload: (file: File) => void;
  isUploading?: boolean;
}

export function FileUpload({ onUpload, isUploading = false }: FileUploadProps) {
  const [dragActive, setDragActive] = useState(false);
  const [fileError, setFileError] = useState<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const validateFile = (file: File): boolean => {
    // 检查文件类型
    if (!isSupportedFileType(file.name)) {
      setFileError(`不支持的文件类型。支持的类型: ${SUPPORTED_FILE_TYPES.join(", ")}`);
      return false;
    }

    // 检查文件大小
    if (file.size > MAX_FILE_SIZE) {
      setFileError(`文件太大。最大允许大小: ${formatFileSize(MAX_FILE_SIZE)}`);
      return false;
    }

    setFileError(null);
    return true;
  };

  const handleDrag = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      const file = e.dataTransfer.files[0];
      if (validateFile(file)) {
        onUpload(file);
      }
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    e.preventDefault();
    if (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0];
      if (validateFile(file)) {
        onUpload(file);
      }
    }
  };

  const handleButtonClick = () => {
    inputRef.current?.click();
  };

  return (
    <div className="w-full">
      <div
        className={`flex h-52 w-full flex-col items-center justify-center rounded-lg border-2 border-dashed p-5 text-center transition-colors ${
          dragActive
            ? "border-blue-500 bg-blue-50 dark:border-blue-400 dark:bg-blue-900/20"
            : "border-gray-300 dark:border-gray-600"
        }`}
        onDragEnter={handleDrag}
        onDragLeave={handleDrag}
        onDragOver={handleDrag}
        onDrop={handleDrop}
      >
        <svg
          className="mb-3 h-10 w-10 text-gray-400 dark:text-gray-500"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth="2"
            d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
          ></path>
        </svg>
        <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
          <span className="font-semibold">点击上传</span> 或拖放文件
        </p>
        <p className="text-xs text-gray-500 dark:text-gray-400">
          支持的文件类型: {SUPPORTED_FILE_TYPES.join(", ")}
        </p>
        <p className="text-xs text-gray-500 dark:text-gray-400">
          最大文件大小: {formatFileSize(MAX_FILE_SIZE)}
        </p>
        
        <input
          type="file"
          id="file-upload"
          ref={inputRef}
          className="hidden"
          onChange={handleChange}
          accept={SUPPORTED_FILE_TYPES.map(type => `.${type}`).join(",")}
          disabled={isUploading}
        />
        
        <Button 
          type="button"
          className="mt-4 bg-blue-600 hover:bg-blue-700"
          onClick={handleButtonClick}
          disabled={isUploading}
        >
          {isUploading ? "上传中..." : "选择文件"}
        </Button>
      </div>

      {fileError && (
        <p className="mt-2 text-sm text-red-500">{fileError}</p>
      )}
    </div>
  );
} 